package com.shi.yibanjia.controller;

import cn.hutool.json.JSONUtil;
import com.shi.yibanjia.common.Result;
import com.shi.yibanjia.common.UserContext;
import com.shi.yibanjia.entity.po.User;
import com.shi.yibanjia.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.shi.yibanjia.common.constant.RedisConstant.*;

@RestController
@RequestMapping("/app/user")
public class UserController {


    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping
    public Result getUserInfo() {
        return Result.ok(UserContext.getUser());
    }

    @PostMapping
    public Result updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        String token=request.getHeader("authorization");
        // 更新数据库
        userService.updateById(user);
        // 更新redis缓存
        stringRedisTemplate.opsForValue().set(TOKEN_PREFIX+token, JSONUtil.toJsonStr(user),TTL,TIME_UNIT);
        return Result.ok();
    }
}
